import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/common.dart';
//DioUtil封装
class DioUtil {
  Future<SharedPreferences> get sp async{
    return await SharedPreferences.getInstance();
  }
  static DioUtil _instance = DioUtil._internal();
  static DioUtil _getInstance() => _instance ??= DioUtil._internal();
//  通过单列获取HttpUtil对象
  static get instance => _getInstance();
  factory DioUtil() => _instance;

  Dio _dio;
  ///取消请求
  cancelRequests(CancelToken token) {
    token.cancel("cancelled");
  }

  ///私有构造方法
  DioUtil._internal() {
    _dio = Dio();
    _dio.options.baseUrl = Common.domain;
    _dio
      ..interceptors.add(InterceptorsWrapper(onRequest: (options) async {
        SharedPreferences sp = await SharedPreferences.getInstance();
        //请求头添加
      _dio.lock();
        String token = sp.getString('token');
        if (token != null) {
          options.headers['Authorization'] = 'Bearer $token';
        }
      _dio.unlock();
        return options;
      },
        onResponse: (response) async {
          LogUtil.v(response);
//        DebugLogUtil.printLog(resp.data.toString(), tag: 'HttpUtil');
        return response.data;
      },

        onError: (DioError error) async {
        _formatError(error);
      }));
  }

  ///error统一处理
  _formatError(DioError error) {
    if (error.type == DioErrorType.CONNECT_TIMEOUT) {
      LogUtil.v("连接超时${error.message}", tag: 'DioUtil');
    } else if (error.type == DioErrorType.SEND_TIMEOUT) {
      LogUtil.v("请求超时${error.message}", tag: 'DioUtil');
    } else if (error.type == DioErrorType.RECEIVE_TIMEOUT) {
      LogUtil.v("响应超时${error.message}", tag: 'DioUtil');
    } else if (error.type == DioErrorType.RESPONSE) {
      LogUtil.v("出现异常${error.message}", tag: 'DioUtil');
    } else if (error.type == DioErrorType.CANCEL) {
      LogUtil.v("请求取消:${error.message}", tag: 'DioUtil');
    } else {
      LogUtil.v('其他异常:${error.toString()}', tag: 'DioUtil');
    }
  }

  //post请求
  Future<Map<String, dynamic>> post(String url,
      {Map<String, dynamic> data, CancelToken cancelToken}) async {
    //代理，findle
//      (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
//        client.findProxy = (uri) {
//          return "PROXY 192.168.0.104:8888";
//        };
//      };

    Response response;
    if (data == null) {
      response = await _dio.post(url, cancelToken: cancelToken);
    } else {
      response = await _dio.post(url, data: data, cancelToken: cancelToken);
    }
    SharedPreferences sp = await SharedPreferences.getInstance();
    if (response.data['code'] == 403) {
      //token过期，重新获取token，并重新请求数据
      sp.setString('token', response.data['result']);
      print('我要重新获取token了---------------------');
      if (data != null) {
        this.post(url, data: data); //重新请求
      } else {
        this.post(url); //重新请求
      }
    }
    return response.data;
  }

  //get请求
  Future<Map<String, dynamic>> get(String url,
      {Map<String, dynamic> data, CancelToken cancelToken}) async {
    //代理，findle
//      (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
//        client.findProxy = (uri) {
//          return "PROXY 192.168.0.104:8888";
//        };
//      };
    SharedPreferences sp = await SharedPreferences.getInstance();
    Response response;
    if (data == null) {
      response = await _dio.get(url, cancelToken: cancelToken);
    } else {
      response =
          await _dio.get(url, queryParameters: data, cancelToken: cancelToken);
    }
    print('aaaaaaa');
    print(response.data);

    if (response.data['code'] == 403) {
      //token过期，重新获取token，并重新请求数据
      sp.setString('token', response.data['result']);
      print('我要重新获取token了---------------------');
      if (data != null) {
        this.get(url, data: data); //重新请求
      } else {
        this.get(url); //重新请求
      }
    }
    return response.data;
  }
}
